package com.liuyc.lib.ui.nestedScroll

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.AttrRes
import androidx.annotation.RequiresApi
import androidx.annotation.StyleRes
import androidx.core.view.NestedScrollingChildHelper
import androidx.core.view.NestedScrollingParent3
import androidx.core.view.NestedScrollingParentHelper
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.liuyc.lib.image.loader.ImageLoaderManager
import com.liuyc.lib.tools.ext.loadChildViewByParentView

class ParentNestedScrollLayout : FrameLayout, NestedScrollingParent3 {

    /**
     * 暂时未研究，但是看很多框架都有用，我们也用起来，目前暂时没什么影响
     */
    private val mNestedScrollingParentHelper: NestedScrollingParentHelper by lazy {
        NestedScrollingParentHelper(this)
    }

    /**
     * 相对我们来说我们是子的处理工具
     * 我们通过这个helper 会通知到我们父类
     */
    private val mNestedScrollingChildHelper: NestedScrollingChildHelper by lazy {
        NestedScrollingChildHelper(this)
    }

    /**
     * 最外层的 recycle
     */
    private lateinit var mParentRecyclerView: RecyclerView

    /**
     * 最外层 recycle 的LayoutManager  必须为：LinearLayoutManager
     */
    private lateinit var mParentRecyclerViewLayoutManager: LinearLayoutManager

    /**
     * 需要嵌套层的 最外层 自定义视图，必须为此视图或者其子类
     */
    private var mChildNestedScrollLinearLayout: ChildNestedScrollLinearLayout? = null


    constructor(context: Context) : super(context) {}
    constructor(
            context: Context, attrs: AttributeSet?
    ) : super(context, attrs) {
    }

    constructor(
            context: Context, attrs: AttributeSet?,
            @AttrRes defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr) {
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(
            context: Context, attrs: AttributeSet?,
            @AttrRes defStyleAttr: Int, @StyleRes defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        // 初始化 最外层的 recycle
        initParentRecycleViewByParentView(this)
        initParentRecycleViewLayoutManager()
        setOnScrollListener()
    }


    /**
     * 从子类view 中找到 recycle
     */
    private fun initParentRecycleViewByParentView(parentViewGroup: ViewGroup) {
        var recyclerView = loadChildViewByParentView<RecyclerView>(parentViewGroup)

        if (recyclerView != null) {

            mParentRecyclerView = recyclerView
        } else {
            throw Exception("未在第一层子类中找到 RecyclerView ")
        }
    }

    /**
     * 初始化 最外层的 recycle  后续可以参考 viewpager2 将recycle 内置
     */
    private fun initParentRecycleViewLayoutManager() {
        mParentRecyclerViewLayoutManager = LinearLayoutManager(context)
        mParentRecyclerView.layoutManager = mParentRecyclerViewLayoutManager
    }


    override fun onStartNestedScroll(child: View, target: View, axes: Int, type: Int): Boolean {

        //最外层的 recycle 当前显示的 item 是否是 第0 个如果是 则事件我们不接管
        if (mParentRecyclerViewLayoutManager.findFirstVisibleItemPosition() == 0) {
            return false
        } else {
            //判断是否是垂直滑动
            return axes == ViewCompat.SCROLL_AXIS_VERTICAL
        }
    }


    override fun onNestedScrollAccepted(child: View, target: View, axes: Int, type: Int) {
        mNestedScrollingParentHelper.onNestedScrollAccepted(child, target, axes, type)
        //向上传递事件
        mNestedScrollingChildHelper.startNestedScroll(axes, type)
    }

    override fun onStopNestedScroll(target: View, type: Int) {
        mNestedScrollingParentHelper.onStopNestedScroll(target, type)
        mNestedScrollingChildHelper.stopNestedScroll(type)
    }

    override fun onNestedScroll(
            target: View,
            dxConsumed: Int,
            dyConsumed: Int,
            dxUnconsumed: Int,
            dyUnconsumed: Int,
            type: Int,
            consumed: IntArray
    ) {
    }

    override fun onNestedScroll(
            target: View,
            dxConsumed: Int,
            dyConsumed: Int,
            dxUnconsumed: Int,
            dyUnconsumed: Int,
            type: Int
    ) {
    }

    override fun onNestedPreScroll(target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) {
        handleScroll(dy, consumed)
    }

    /**
     * 处理滚动事件
     */
    private fun handleScroll(dy: Int, consumed: IntArray) {
        getChildNestedScrollLinearLayout()?.let {
            if (it.top > 0) {
                mParentRecyclerView?.scrollBy(0, dy);
            } else {
                it.receiverScrollByParent(dy, consumed)
            }
        }
    }

    /**
     * 获取嵌套滚动视图
     */
    private fun getChildNestedScrollLinearLayout(): ChildNestedScrollLinearLayout? {

        if (mChildNestedScrollLinearLayout != null) {
            return mChildNestedScrollLinearLayout;
        }

        mChildNestedScrollLinearLayout =
                getChildNestedScrollLinearLayoutByParentRecycleLayoutManager()

        return mChildNestedScrollLinearLayout;
    }

    /**
     * 滚动去查找我们 需要嵌套滚动层
     */
    private fun getChildNestedScrollLinearLayoutByParentRecycleLayoutManager(): ChildNestedScrollLinearLayout? {
        var childNestedScrollLinearLayout: ChildNestedScrollLinearLayout? = null

        val firstVisibleItemPosition = mParentRecyclerViewLayoutManager.findFirstVisibleItemPosition()
        var childView = mParentRecyclerViewLayoutManager.findViewByPosition(firstVisibleItemPosition)
        if (childView is ChildNestedScrollLinearLayout) {
            childNestedScrollLinearLayout = childView
        }

        return childNestedScrollLinearLayout
    }

    /**
     * 设置 最外层 adapter
     */
    fun setAdapter(adapter: RecyclerView.Adapter<*>?) {
        mParentRecyclerView.adapter = adapter
    }

    /**
     * 获取 最外层 adapter
     */
    fun getAdapter(): RecyclerView.Adapter<*>? {
        return mParentRecyclerView.getAdapter()
    }

    /**
     * 滑动到顶部
     * TODO  暂未实现
     */
    fun toTop(){
        toScroll(0)
    }

    private fun toScroll(dy: Int){

    }

    fun setOnScrollListener(){
        mParentRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                checkLoadImage(newState)
            }
        })
    }

    private fun checkLoadImage(newState: Int){
        when(newState){
            RecyclerView.SCROLL_STATE_IDLE ->{
                ImageLoaderManager.getInstance().resumeLoadImage(context)
            }
            else ->{
                ImageLoaderManager.getInstance().pauseLoadImage(context)
            }
        }
    }

    private fun checkScrollToBottom(){


    }

}